﻿using Pb;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;

public class DDZGame : Game {
    
    EginUser user = EginUser.Instance;
    EginDDZ ddz = EginDDZ.Instance;
    //玩家
    public List<DDZUser> Users;

    //房间号
    public UILabel roomidLable;
    public GameObject roomObj;
    //倍数显示
    public UILabel multiplyLable;

    //root
    public GameObject Root;


    //音效
    public List<AudioClip> cardsSingleMen;
    public List<AudioClip> cardsSingleWomen;
    public List<AudioClip> cardsTwinMen;
    public List<AudioClip> cardsTwinWomen;
    public List<AudioClip> muchThreeMen;
    public List<AudioClip> muchThreeWomen;
    public List<AudioClip> Commond;

    //音效
    public List<AudioClip> textMen;
    public List<AudioClip> textWomen;

    public GameObject ExitButton;
    public GameObject ChatButton;
    public GameObject SetButton;

    //暂时存进内存
    private DDZCardsControl ddzCardsControl;
    private GameObject LastThreeCards;
    private GameObject CallScore;
    private GameObject LastThreeCardsShow;
    private GameObject Time;
    //private GameObject Ready;

    #region  斗地主收到的服务器消息

    #endregion



    private string[] ddzText = {
        "别吵了，别吵了，专心玩游戏吧！",
        "和你合作真是太愉快了！",
        "快点啊，等的我花都谢了！",
        "你这么牛X你家里人知道吗？",
        "土豪我们做朋友吧",
        "小伙伴你和地主是一家吧！",
        "怎么又掉线了，网络也太差了吧！"
    };

    void Awake()
    {
        base.StartGameSocket();
        SocketManager.Instance.socketListener = this;
        UIEventListener.Get(ExitButton).onClick = ButtonClick;
        UIEventListener.Get(ChatButton).onClick = ButtonClick;
        UIEventListener.Get(SetButton).onClick = ButtonClick;

    }
    void ButtonClick(GameObject button)
    { 
        if (button.name == "ExitButton")
        {
            //发送离开消息
            if (EginDDZ.Instance.createrUid == (int.Parse)(EginUser.Instance.Uid))
            {
                RoomDismissRequest lg = new Pb.RoomDismissRequest { RoomId = EginDDZ.Instance.roomId };
                SocketManager socketManager = SocketManager.Instance;
                socketManager.SendProtobuf1(lg, MsgId.RoomDismissRequest);
                
            }
            else
            {
                RoomLeaveRequest lg = new Pb.RoomLeaveRequest { RoomId = EginDDZ.Instance.roomId };
                SocketManager socketManager = SocketManager.Instance;
                socketManager.SendProtobuf1(lg, MsgId.RoomLeaveRequest);
                
            }
        }
        else if (button.name == "ChatButton")
        {
           
            GameObject DDZChat = NGUITools.AddChild(Root, (GameObject)(Resources.Load(GameDDZPrafabPath.DDZChat)));
        }
        else if (button.name == "SetButton")
        {
            // DNSet
            GameObject Set = NGUITools.AddChild(Root, (GameObject)(Resources.Load(GameDNPrafabPath.Set)));
        }
    }

    void Start()
    {
        //加载玩家
        LoadUser();
        //房间号显示
        if (user.ControlScene == 1)
        {
            string tempRoomID = ddz.roomId.ToString();
            roomidLable.text = tempRoomID;
        }
        else
        {
            roomObj.SetActive(false);
        }
        if (ddz.isReconnect == true)
        {
            ddz.isReconnect = false;
            DDZReconnect();
        }
        //StartCoroutine(AdvanceLoad()) ;
        //加载ready按钮
        for (int i=0;i<user.gameUserInfoList.Count;i++) {
            if (ddz.seatId == user.gameUserInfoList[i].SeatId) {
                if (user.gameUserInfoList[i].SeatStatus == SEAT_STATUS.Sit)
                {
                    GameObject Ready = NGUITools.AddChild(Root, (GameObject)(Resources.Load(GameDDZPrafabPath.Ready)));
                }
                
            }
        }
    }

    /// <summary>
    /// 监听服务器消息
    /// </summary>
    /// <param name="data"></param>
    public override void SocketReceiveMessage(byte[] data)
    {
        base.SocketReceiveMessage(data);
        byte[] dataLength = data.Skip(0).Take(2).ToArray();
        byte[] dataId = data.Skip(2).Take(4).ToArray();
        byte[] dataConcent = data.Skip(data.Length - (data.Length - 4)).ToArray();
        int TempMsgID = ProtoDataToMsg.Byte2ushort(dataId);

        #region 斗地主玩家加入离开房间返回  准备消息
        if (TempMsgID == MsgId.RoomUserInfoBroadcast)
        {
            Pb.RoomUserInfoBroadcast newpb = Pb.RoomUserInfoBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            if (newpb.UserInfo.SeatStatus == SEAT_STATUS.Sit)
            {
                //加入房间
                user.gameUserInfoList.Add(newpb.UserInfo);
                int tempIndex = ddz.returnOtherSeatIndex(newpb.UserInfo.SeatId);
                Users[tempIndex].gameObject.SetActive(true);
                Users[tempIndex].seatID = newpb.UserInfo.SeatId;
                Users[tempIndex].sex = newpb.UserInfo.Sex;
                Users[tempIndex].username.text = newpb.UserInfo.Nickname;
                if (user.ControlScene == 1)
                {
                    string str = user.ReturnMoney(newpb.UserInfo.Score);
                    Users[tempIndex].Coin.text = str;
                }
                else
                {
                    string str = user.ReturnMoney(newpb.UserInfo.BagCoinCount);
                    Users[tempIndex].Coin.text = str;
                }
                Users[tempIndex].ShowCharacter(0);

            }
            else if (newpb.UserInfo.SeatStatus == SEAT_STATUS.Leave)
            {
                if (ddz.roomStatus != ROOM_STATUS.Gaming)
                {
                    //离开房间
                    for (int i = 0; i < user.gameUserInfoList.Count; i++)
                    {
                        if (newpb.UserInfo.SeatId == user.gameUserInfoList[i].SeatId)
                        {
                            user.gameUserInfoList.RemoveAt(i);
                            int tempIndex = ddz.returnOtherSeatIndex(newpb.UserInfo.SeatId);
                            Users[tempIndex].gameObject.SetActive(false);
                            break;
                        }
                    }
                }
            }
            //准备广播
            else if (newpb.UserInfo.SeatStatus == SEAT_STATUS.Ready) {
                int tempIndex = ddz.returnOtherSeatIndex(newpb.UserInfo.SeatId);
                if (ddz.roomStatus != ROOM_STATUS.Gaming)
                {
                    Users[tempIndex].ReadyStatus.gameObject.SetActive(true);
                }
                if(ddz.seatId== newpb.UserInfo.SeatId)
                    Destroy(GameObject.Find("Ready"));

                if (Users[tempIndex].gameObject.activeSelf == false && newpb.UserInfo.AvatarId != 0)
                {
                    Debug.Log(111);
                    user.gameUserInfoList.Add(newpb.UserInfo);
                    Users[tempIndex].gameObject.SetActive(true);
                    Users[tempIndex].seatID = newpb.UserInfo.SeatId;
                    Users[tempIndex].sex = newpb.UserInfo.Sex;
                    Users[tempIndex].username.text = newpb.UserInfo.Nickname;
                    if (user.ControlScene == 1)
                    {
                        string str = user.ReturnMoney(newpb.UserInfo.Score);
                        Users[tempIndex].Coin.text = str;
                    }
                    else
                    {
                        string str = user.ReturnMoney(newpb.UserInfo.BagCoinCount);
                        Users[tempIndex].Coin.text = str;
                    }
                    Users[tempIndex].ShowCharacter(0);
                }

            }
        }
        else if (TempMsgID == MsgId.RoomReadyResponse)
        {
            Pb.RoomReadyResponse newpb = Pb.RoomReadyResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            Users[0].ReadyStatus.gameObject.SetActive(true);
        }
        //离开房间
        else if (TempMsgID == MsgId.RoomLeaveResponse)
        {
            Pb.RoomLeaveResponse newpb = Pb.RoomLeaveResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            if (newpb.Status == STATUS.Success)
            {
                EginUser.Instance.gameUserInfoList.Clear();
                SceneManager.LoadScene(ScenePath.Hall);
                //Application.LoadLevelAsync(ScenePath.GameDDZ);
                
            }
            else
            {
                user.logMsg = newpb.Msg;
                GameObject Set = NGUITools.AddChild(Root, (GameObject)(Resources.Load("LogMsg")));
            }
        }
        else if (TempMsgID == MsgId.RoomDismissBroadcast)
        {
            Pb.RoomDismissBroadcast newpb = Pb.RoomDismissBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            EginUser.Instance.gameUserInfoList.Clear();
            SceneManager.LoadScene(ScenePath.Hall);
        }
        //处理更改seatid
        else if (TempMsgID == MsgId.NewSeatIdNotification)
        {
            Pb.NewSeatIdNotification newpb = Pb.NewSeatIdNotification.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            for (int j = 0; j < user.gameUserInfoList.Count; j++)
            {
                if (ddz.lordSid == user.gameUserInfoList[j].SeatId)
                {
                    for (int i = 0; i < newpb.OldSidList.Count; i++)
                    {
                        if (user.gameUserInfoList[j].Uid == newpb.OldSidList[i])
                        {
                            ddz.lordSid = newpb.NewSidList[i];
                        }
                    }
                }

            }
            for (int i = 0; i < newpb.OldSidList.Count; i++)
            {
                if (newpb.OldSidList[i] == (int.Parse)(user.Uid))
                {
                    ddz.seatId = newpb.NewSidList[i];
                    ddz.SortSeatId();
                    break;
                }

            }

            for (int i = 0; i < newpb.OldSidList.Count; i++)
            {
                for (int j = 0; j < user.gameUserInfoList.Count; j++)
                {
                    if (user.gameUserInfoList[j].Uid == newpb.OldSidList[i])
                    {
                        user.gameUserInfoList[j].SeatId = newpb.NewSidList[i];
                        break;
                    }
                }
            }
            LoadUser();
        }
        #endregion

        #region 斗地主Game消息
        //开始叫分
        else if (TempMsgID == MsgId.DdzCallBeginNotification)
        {
            Pb.DdzCallBeginNotification newpb = Pb.DdzCallBeginNotification.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            ddz.roomStatus = newpb.RoomStatus;
            ddz.currentRound = newpb.CurrentRound;
            //关闭ready状态
            HideReadyStatus();
            //生成cards
            List<int> ownCards = newpb.CardList.ToList();
            GameObject DDZCards = NGUITools.AddChild(Root, (GameObject)(Resources.Load(GameDDZPrafabPath.DDZCards)));
            ddzCardsControl = DDZCards.GetComponent<DDZCardsControl>();
            ddzCardsControl.StartShowCards(ownCards);
            //加载叫分预设
            if (ddz.seatId == newpb.TurnSid) {
                StartCoroutine(WaitShowCallScore());
                
            }
            //加载底牌 三张牌
            LastThreeCards = NGUITools.AddChild(Root, (GameObject)(Resources.Load(GameDDZPrafabPath.LastThreeCards)));
            LoadTimeObj(newpb.TurnSid, false);

            multiplyLable.text = "0";

        }
        //自己叫分返回
        else if (TempMsgID == MsgId.DdzCallResponse)
        {
            Pb.DdzCallResponse newpb = Pb.DdzCallResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            if (newpb.Status == STATUS.Success) {

            }
        }
        //叫分广播
        else if (TempMsgID == MsgId.DdzCallBroadcast)
        {
            Pb.DdzCallBroadcast newpb = Pb.DdzCallBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            if (newpb.IsFlow) {
                Destroy(ddzCardsControl.gameObject);
                HideSayScore();
                Destroy(LastThreeCards);
                Destroy(CallScore);
                Destroy(Time);
                //GameObject Ready = NGUITools.AddChild(Root, (GameObject)(Resources.Load(GameDDZPrafabPath.Ready)));
            }
            else
            {
                if (newpb.SeatId == ddz.seatId) {
                    Destroy(CallScore);
                }
                int tempIndex = ddz.returnOtherSeatIndex(newpb.SeatId);
                Users[tempIndex].SayScore.gameObject.SetActive(true);
                Users[tempIndex].SayScore.spriteName = newpb.CallMultiple.ToString();
                //加载叫分预设
                if (newpb.NextSid == 0)
                {
                    Destroy(LastThreeCards);
                }
                else {
                    if (ddz.seatId == newpb.NextSid)
                    {
                        if (newpb.Multiply == 0) {
                            CallScore = NGUITools.AddChild(Root, (GameObject)(Resources.Load(GameDDZPrafabPath.CallScore)));
                        }
                        else if (newpb.Multiply == 1)
                        {
                            CallScore = NGUITools.AddChild(Root, (GameObject)(Resources.Load(GameDDZPrafabPath.CallScore2)));
                        }
                        else if (newpb.Multiply == 2)
                        {
                            CallScore = NGUITools.AddChild(Root, (GameObject)(Resources.Load(GameDDZPrafabPath.CallScore3)));
                        }
                    }
                }
            }
            //叫分音效
            for (int i = 0; i < user.gameUserInfoList.Count; i++)
            {
                if (user.gameUserInfoList[i].SeatId == newpb.SeatId) {
                    if (user.gameUserInfoList[i].Sex == SEX.Male)
                    {
                        SoundModel.PlaySound(muchThreeMen[newpb.CallMultiple]);
                    }
                    else {
                        SoundModel.PlaySound(muchThreeWomen[newpb.CallMultiple]);
                    }
                }
            }
            if (newpb.NextSid != 0)
            {
                LoadTimeObj(newpb.NextSid, true);
            }
            
        }
        //游戏正式开始 地主的三张牌
        else if (TempMsgID == MsgId.DdzGameBeginBroadcast)
        {
            Pb.DdzGameBeginBroadcast newpb = Pb.DdzGameBeginBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            HideSayScore();
            Destroy(LastThreeCards);
            //显示三张牌到上面
            LastThreeCardsShow = NGUITools.AddChild(Root, (GameObject)(Resources.Load(GameDDZPrafabPath.LastThreeCardsShow)));
            DDZLastThreeCardsShow ddzLastThreeCardsShow = LastThreeCardsShow.GetComponent<DDZLastThreeCardsShow>();
            for (int i=0;i<newpb.LordCardList.Count;i++) {
                ddzLastThreeCardsShow.topShowThreeCards[i].spriteName = newpb.LordCardList[i].ToString();
            }
            //显示当前倍数
            multiplyLable.text = newpb.Multiply.ToString();
            //处理地主
            int tempIndex = ddz.returnOtherSeatIndex(newpb.LordSid);
            Users[tempIndex].ShowCharacter(newpb.LordSid);
            if (newpb.LordSid == ddz.seatId)
            {
                //自己是地主
                ddzCardsControl.AddThreeCards(newpb.LordCardList.ToList());
                //显示出牌按钮
                ddzCardsControl.ShowOutCardBtnObj();
            }
            else {
                //他人是地主
                ddzCardsControl.OtherCardRemainderShow(3,newpb.LordSid);
            }
            ddz.nextSid = newpb.LordSid;
            ddz.lordSid = newpb.LordSid;
            LoadTimeObj(newpb.LordSid, true);
        }
        //自己的出牌消息返回
        else if (TempMsgID == MsgId.DdzPlayResponse)
        {
            Pb.DdzPlayResponse newpb = Pb.DdzPlayResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
        }
        //出牌广播
        else if (TempMsgID == MsgId.DdzPlayBroadcast)
        {
            Pb.DdzPlayBroadcast newpb = Pb.DdzPlayBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            ddz.nextSid = newpb.NextSid;
            if (newpb.PokerType != POKER_TYPE.Pass)
            {
                ddzCardsControl.lastPokerType = newpb.PokerType;
                ddzCardsControl.lastSeatId = newpb.SeatId;
                ddzCardsControl.lastOutCards = newpb.CardList.ToList();
                //显示过牌UI
                //显示剩余牌张数
                ddzCardsControl.OtherCardRemainderShow(-newpb.CardList.ToList().Count, newpb.SeatId);
            }
            
            //把出的牌显示出来
            ddzCardsControl.ShowPlayerOutCard(newpb.CardList.ToList(), newpb.SeatId,newpb.PokerType,newpb.NextSid);
            //自己出牌出的牌隐藏掉 重新排序 把出牌的按钮初始化
            if (newpb.SeatId == ddz.seatId) {
                ddzCardsControl.RemoveOutCards(newpb.CardList.ToList());
                ddzCardsControl.InitBtn();
                if (newpb.IsRobot)
                {
                    ddzCardsControl.CancelAutoBtnFather.SetActive(true);
                }
            }
            //该出牌的显示出牌按钮
            if (ddz.nextSid == ddz.seatId) {
                //显示当前玩家出牌按钮
                ddzCardsControl.ShowOutCardBtnObj();
                
            }
            multiplyLable.text = newpb.Multiply.ToString();
            LoadTimeObj(newpb.NextSid, true);
            //出牌音效
            int z = 0;
            if (newpb.CardList.Count > 0) {
                z = newpb.CardList[0];
            }
            
            PlaySound(newpb.PokerType, z, newpb.SeatId);

            //显示托管状态
            if (newpb.IsRobot)
            {
                int tempIndex = ddz.returnOtherSeatIndex(newpb.SeatId);
                Users[tempIndex].AutoStatus.SetActive(true);

            }
        }
        //游戏结算
        else if (TempMsgID == MsgId.DdzGameOverBroadcast)
        {
            Pb.DdzGameOverBroadcast newpb = Pb.DdzGameOverBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            Destroy(Time);
            /*消息ID93消息内容{ "nextRound": true, "userList": [
             *  { "seatId": 1, "roundScore": -600, "totalScore": -600, "totalRank": 2, "handCardList": [ 1, 7, 12, 14, 17, 18, 22, 27, 28, 29, 33, 38, 40, 46, 47, 53 ] },
             *  { "seatId": 2, "roundScore": -600, "totalScore": -600, "totalRank": 2, "handCardList": [ 5, 6, 8, 13, 15, 16, 21, 31, 32, 35, 36, 39, 41, 42, 43, 51, 52 ] },
             *  { "seatId": 3, "roundScore": 1200, "totalScore": 1200, "totalRank": 1 } ],
             *  "BagCoinCount": 9999800, "multiply": 6 }*/
            StartCoroutine(HideAutoBtn());
            if (ddzCardsControl != null) {
                ddzCardsControl.CancelAutoBtnFather.SetActive(false);
            }
            
            HideAutoStatus();
            //剩余的牌显示出来

            Destroy(LastThreeCardsShow);
            user.coinCount = newpb.BagCoinCount.ToString();
            ddz.roomStatus = newpb.RoomStatus;
            List<GameOverUserInfo> gameOverUserInfo = newpb.UserList.ToList();
            for (int i = 0; i < gameOverUserInfo.Count; i++)
            {
                if (ddzCardsControl != null)
                {
                    ddzCardsControl.ShowCardForGameover(gameOverUserInfo[i].HandCardList.ToList(), gameOverUserInfo[i].SeatId);
                }
            }

            if (user.ControlScene == 1)
            {
                for (int i = 0; i < gameOverUserInfo.Count; i++)
                {

                    int tempIndex = ddz.returnOtherSeatIndex(gameOverUserInfo[i].SeatId);
                    user.gameUserInfoList[i].Score += gameOverUserInfo[i].RoundScore;
                    string str = user.ReturnMoney(user.gameUserInfoList[i].Score);
                    Users[tempIndex].Coin.text = str;
                }
            }
            else
            {
                for (int i = 0; i < gameOverUserInfo.Count; i++)
                {

                    int tempIndex = ddz.returnOtherSeatIndex(gameOverUserInfo[i].SeatId);
                    user.gameUserInfoList[i].BagCoinCount += gameOverUserInfo[i].RoundScore;
                    string str = user.ReturnMoney(user.gameUserInfoList[i].BagCoinCount);
                    Users[tempIndex].Coin.text = str;

                    if (user.gameUserInfoList[i].SeatId == ddz.seatId)
                    {
                        user.gameUserInfoList[i].BagCoinCount = newpb.BagCoinCount;
                    }

                }
            }
            //提前隐藏地主信息
            int tempIndex1 = ddz.returnOtherSeatIndex(ddz.lordSid);
            for (int i = 0; i < user.gameUserInfoList.Count; i++)
            {
                if (ddz.lordSid == user.gameUserInfoList[i].SeatId)
                {
                    Users[tempIndex1].ShowCharacter(0);
                    Users[tempIndex1].LordStatus.SetActive(false);
                }
            }
            //加载游戏结束界面
            GameObject GameOver = NGUITools.AddChild(Root, (GameObject)(Resources.Load(GameDDZPrafabPath.DDZGameOver)));
            DDZGameOver ddzGameOver = GameOver.GetComponent<DDZGameOver>();
            ddzGameOver.GameoverEvent(newpb.NextRound, gameOverUserInfo,newpb.BaseScore,newpb.Multiply);
            ddzGameOver.nextover1 = newpb.NextRound;
            //ddzGameOver.newpb = newpb;
        }
        #endregion

        #region 文字表情聊天
        else if (TempMsgID == MsgId.RoomChatBroadcast)
        {
            Pb.RoomChatBroadcast newpb = Pb.RoomChatBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            StartCoroutine(TextFaceChat(newpb));
        }
        #endregion

        
        else if (TempMsgID == MsgId.UserCancelRobotResponse)
        {
            Pb.UserCancelRobotResponse newpb = Pb.UserCancelRobotResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
        }
        //取消托管
        else if (TempMsgID == MsgId.UserCancelRobotBroadcast)
        {
            Pb.UserCancelRobotBroadcast newpb = Pb.UserCancelRobotBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            int tempIndex = ddz.returnOtherSeatIndex(newpb.SeatId);
            Users[tempIndex].AutoStatus.SetActive(false);
        }
        //网络异常
        else if (TempMsgID == MsgId.NetWorkAbnormalMessage)
        {
            GameObject NetWorkAbnormal = NGUITools.AddChild(GameObject.Find("UI Root"), (GameObject)(Resources.Load("NetWorkAbnormal")));
        }
    }



    IEnumerator WaitShowCallScore() {
        yield return new WaitForSeconds(1.7f);
        CallScore = NGUITools.AddChild(Root, (GameObject)(Resources.Load(GameDDZPrafabPath.CallScore)));
    }

    /// <summary>
    /// 加载玩家状态
    /// </summary>
    void LoadUser()
    {
        ddz.SortSeatId();        
        for (int i = 0; i < user.gameUserInfoList.Count; i++)
        {
            int tempIndex = ddz.returnOtherSeatIndex(user.gameUserInfoList[i].SeatId);
            Users[tempIndex].gameObject.SetActive(true);
            Users[tempIndex].seatID = user.gameUserInfoList[i].SeatId;
            Users[tempIndex].sex = user.gameUserInfoList[i].Sex;
            Users[tempIndex].username.text = user.gameUserInfoList[i].Nickname;            
            if (user.ControlScene == 1)
            {
                string str = user.ReturnMoney(user.gameUserInfoList[i].Score);
                Users[tempIndex].Coin.text = str;
            }
            else
            {
                string str = user.ReturnMoney(user.gameUserInfoList[i].BagCoinCount);
                Users[tempIndex].Coin.text = str;
            }
            Users[tempIndex].ShowCharacter(0);

            if (user.gameUserInfoList[i].SeatStatus == SEAT_STATUS.Ready)
            {
                Users[tempIndex].ReadyStatus.gameObject.SetActive(true);
            }
        }
        
    }
    /// <summary>
    /// 隐藏ready
    /// </summary>
    void HideReadyStatus() {
        for (int i=0;i<Users.Count;i++) {
            Users[i].ReadyStatus.gameObject.SetActive(false);
        }
    }
    /// <summary>
    /// 隐藏sayscore
    /// </summary>
    void HideSayScore()
    {
        for (int i = 0; i < Users.Count; i++)
        {
            Users[i].SayScore.gameObject.SetActive(false);
        }
    }

    void HideAutoStatus()
    {
        for (int i = 0; i < Users.Count; i++)
        {
            Users[i].AutoStatus.SetActive(false);
        }
    }
    IEnumerator HideAutoBtn()
    {
        yield return new WaitForSeconds(0.2f);
        if (ddzCardsControl != null)
        {
            ddzCardsControl.CancelAutoBtnFather.SetActive(false);
        }
    }

    /// <summary>
    /// 文字表情聊天   
    /// </summary>
    /// <param name="newpb"></param>
    /// <returns></returns>  
    IEnumerator TextFaceChat(RoomChatBroadcast newpb)
    {
        int tempIndex = 0;
        for (int i = 0; i < user.gameUserInfoList.Count; i++)
        {
            if (newpb.FromUid == user.gameUserInfoList[i].Uid)
            {
                int tempSeatid = user.gameUserInfoList[i].SeatId;
                tempIndex = ddz.returnOtherSeatIndex(tempSeatid);
                if (newpb.MsgType == RoomChatType.TextId)
                {
                    Users[tempIndex].textObj.SetActive(true);
                    Users[tempIndex].text.text = ddzText[int.Parse(newpb.Content) - 1];
                    if (user.gameUserInfoList[i].Sex == SEX.Male)
                    {
                        SoundModel.PlaySound(textMen[int.Parse(newpb.Content) - 1]);
                    }
                    else
                    {
                        SoundModel.PlaySound(textWomen[int.Parse(newpb.Content) - 1]);
                    }
                }
                else if (newpb.MsgType == RoomChatType.MovieClip)
                {
                    Users[tempIndex].face.gameObject.SetActive(true);
                    Users[tempIndex].face.spriteName = newpb.Content;
                }

            }
        }
        yield return new WaitForSeconds(2.5f);
        Users[tempIndex].textObj.SetActive(false);
        Users[tempIndex].face.gameObject.SetActive(false);
    }

    #region  出牌音效

    /// <summary>
    /// 出牌音效
    /// </summary>
    /// <param name="type"></param>
    /// <param name="card"></param>
    /// <param name="seatid"></param>
    private void PlaySound(POKER_TYPE type,int card,int seatid) {
        int tempIndex = ddz.returnOtherSeatIndex(seatid);
        SEX sex = SEX.Unknown;
        AudioClip ac=new AudioClip();
        for (int i = 0; i < user.gameUserInfoList.Count; i++)
        {
            if (user.gameUserInfoList[i].SeatId == seatid)
            {
                if (user.gameUserInfoList[i].Sex == SEX.Male)
                {
                    sex = SEX.Male;
                }
                else
                {
                    sex = SEX.Female;
                }
            }
        }
        if (type == POKER_TYPE.Pass)
        {
            if (sex == SEX.Male)
            {
                ac = cardsSingleMen[13];
            }
            else
            {
                ac = cardsSingleWomen[13];
            }
        }
        else if (type == POKER_TYPE.Single)
        {
            if (card == 53)
            {
                card = 14;
            }
            else if (card == 54)
            {
                card = 15;
            }
            else
            {
                card = card % 13;
            }
            if (sex == SEX.Male)
            {
                ac = cardsSingleMen[card];
            }
            else
            {
                ac = cardsSingleWomen[card];
            }
        }
        else if (type == POKER_TYPE.Twin)
        {
            card = card % 13;
            if (sex == SEX.Male)
            {
                ac = cardsTwinMen[card];
            }
            else
            {
                ac = cardsTwinWomen[card];
            }
        }
        else if (type == POKER_TYPE.Triple)
        {
            if (sex == SEX.Male)
            {
                ac = muchThreeMen[4];
            }
            else
            {
                ac = muchThreeWomen[4];
            }
        }
        else if (type == POKER_TYPE.TripleWithSingle)
        {
            if (sex == SEX.Male)
            {
                ac = muchThreeMen[5];
            }
            else
            {
                ac = muchThreeWomen[5];
            }
        }
        else if (type == POKER_TYPE.TripleWithTwin)
        {
            if (sex == SEX.Male)
            {
                ac = muchThreeMen[6];
            }
            else
            {
                ac = muchThreeWomen[6];
            }
        }
        else if (type == POKER_TYPE.StraightSingle)
        {
            if (sex == SEX.Male)
            {
                ac = muchThreeMen[7];
            }
            else
            {
                ac = muchThreeWomen[7];
            }
            GameObject Shunzi = NGUITools.AddChild(gameObject, (GameObject)(Resources.Load("GameDDZ/Animation/Shunzi")));
            if (tempIndex == 0)
            {
                Shunzi.transform.localPosition = new Vector3(-16, -77, 0);
            }
            else if (tempIndex == 2)
            {
                Shunzi.transform.localPosition = new Vector3(-197, 170, 0);
            }
            else if (tempIndex == 1)
            {
                Shunzi.transform.localPosition = new Vector3(161, 170, 0);
            }
        }
        else if (type == POKER_TYPE.StraightTwin)
        {
            if (sex == SEX.Male)
            {
                ac = muchThreeMen[8];
            }
            else
            {
                ac = muchThreeWomen[8];
            }
            GameObject Liandui = NGUITools.AddChild(gameObject, (GameObject)(Resources.Load("GameDDZ/Animation/Liandui")));
            Liandui.transform.localScale = new Vector3((float)0.4, (float)0.4, 0);
            if (tempIndex == 0)
            {
                Liandui.transform.localPosition = new Vector3(-16, -77, 0);
            }
            else if (tempIndex == 2)
            {
                Liandui.transform.localPosition = new Vector3(-200, 174, 0);
            }
            else if (tempIndex == 1)
            {
                Liandui.transform.localPosition = new Vector3(158, 174, 0);
            }
        }
        else if (type == POKER_TYPE.FourWithSingle)
        {
            if (sex == SEX.Male)
            {
                ac = muchThreeMen[9];
            }
            else
            {
                ac = muchThreeWomen[9];
            }
        }
        else if (type == POKER_TYPE.FourWithTwin)
        {
            if (sex == SEX.Male)
            {
                ac = muchThreeMen[10];
            }
            else
            {
                ac = muchThreeWomen[10];
            }
        }
        else if (type == POKER_TYPE.FourBomb)
        {
            if (sex == SEX.Male)
            {
                ac = muchThreeMen[11];
            }
            else
            {
                ac = muchThreeWomen[11];
            }
            GameObject Zhadan = NGUITools.AddChild(gameObject, (GameObject)(Resources.Load("GameDDZ/Animation/Zhadan")));
        }
        else if (type == POKER_TYPE.KingBomb)
        {
            if (sex == SEX.Male)
            {
                ac = muchThreeMen[12];
            }
            else
            {
                ac = muchThreeWomen[12];
            }
            GameObject Zhadan = NGUITools.AddChild(gameObject, (GameObject)(Resources.Load("GameDDZ/Animation/Zhadan")));
        }
        else if (type == POKER_TYPE.PlanePure || type == POKER_TYPE.PlaneWithSingle || type == POKER_TYPE.PlaneWithTwin)
        {
            if (sex == SEX.Male)
            {
                ac = muchThreeMen[13];
            }
            else
            {
                ac = muchThreeWomen[13];
            }
            GameObject Feiji = NGUITools.AddChild(gameObject, (GameObject)(Resources.Load("GameDDZ/Animation/Feiji")));
            Feiji.transform.localScale = new Vector3((float)0.4,(float)0.4,0);
            if (tempIndex == 0)
            {
                Feiji.transform.localPosition = new Vector3(-16, -77, 0);
            }
            else if (tempIndex == 2)
            {
                Feiji.transform.localPosition = new Vector3(-199, 178, 0);
            }
            else if (tempIndex == 1)
            {
                Feiji.transform.localPosition = new Vector3(164, 178, 0);
            }
        }
        SoundModel.PlaySound(ac);
    }
    #endregion  出牌音效


    #region 重连
    /// <summary>
    /// 斗地主重连
    /// </summary>
    void DDZReconnect()
    {
        DdzReconnectRoomResponse newpb = ddz.ddzReconnectRoomResponse;
        //加载准备状态
        if (newpb.RoomInfo.RoomStatus != ROOM_STATUS.Gaming) {
            for (int i = 0; i < user.gameUserInfoList.Count; i++)
            {
                if (user.gameUserInfoList[i].SeatStatus == SEAT_STATUS.Ready)
                {
                    int tempIndex = ddz.returnOtherSeatIndex(user.gameUserInfoList[i].SeatId);
                    Users[tempIndex].ReadyStatus.gameObject.SetActive(true);
                    Debug.Log("重连ready");
                }
            }
        }
        else if (newpb.RoomInfo.RoomStatus == ROOM_STATUS.Gaming) {
            HideReadyStatus();
            //生成cards 显示自己的牌
            List<int> ownCards = newpb.CardList.ToList();
            GameObject DDZCards = NGUITools.AddChild(Root, (GameObject)(Resources.Load(GameDDZPrafabPath.DDZCards)));
            ddzCardsControl = DDZCards.GetComponent<DDZCardsControl>();
            ddzCardsControl.ReconnectShowCards(ownCards);
            //加载地主
            Debug.Log("重连lord_id" + newpb.LordSid);
            if (newpb.LordSid != 0)
            {
                int tempIndex = ddz.returnOtherSeatIndex(newpb.LordSid);
                Users[tempIndex].ShowCharacter(newpb.LordSid);
                //显示左右玩家剩余牌
                for (int i = 0; i < user.gameUserInfoList.Count; i++)
                {
                    if (user.gameUserInfoList[i].SeatId != ddz.seatId) {
                        ddzCardsControl.OtherCardRemainderShow(user.gameUserInfoList[i].RemainCount, user.gameUserInfoList[i].SeatId);
                    }
                }
                //三张牌显示出来
                LastThreeCardsShow = NGUITools.AddChild(Root, (GameObject)(Resources.Load(GameDDZPrafabPath.LastThreeCardsShow)));
                DDZLastThreeCardsShow ddzLastThreeCardsShow = LastThreeCardsShow.GetComponent<DDZLastThreeCardsShow>();
                for (int i = 0; i < newpb.LordCardList.Count; i++)
                {
                    ddzLastThreeCardsShow.topShowThreeCards[i].spriteName = newpb.LordCardList[i].ToString();
                }
                //上家的牌存进去
                for (int i = 0; i < newpb.PlayList.Count;i++) {
                    if (newpb.PlayList[i].PokerType != POKER_TYPE.Pass)
                    {
                        ddzCardsControl.lastPokerType = newpb.PlayList[i].PokerType;
                        ddzCardsControl.lastSeatId = newpb.PlayList[i].SeatId;
                        ddzCardsControl.lastOutCards = newpb.PlayList[i].CardList.ToList();
                    }
                    //玩家出的牌显示出来
                    ddzCardsControl.ShowPlayerOutCard(newpb.PlayList[i].CardList.ToList(), newpb.PlayList[i].SeatId, newpb.PlayList[i].PokerType, newpb.TurnSid);
                }

                //该出牌的显示出牌按钮
                if (ddz.nextSid == ddz.seatId)
                {
                    //显示当前玩家出牌按钮
                    ddzCardsControl.ShowOutCardBtnObj();
                }
                //显示倍数
                multiplyLable.text = newpb.RoomInfo.Multiply.ToString();

            }
            else {
                if (newpb.TurnSid != 0) {
                    //叫多少分(未写)
                    for (int i = 0; i < user.gameUserInfoList.Count; i++)
                    {
                        int tempIndex = ddz.returnOtherSeatIndex(user.gameUserInfoList[i].SeatId);
                    }
                    Debug.Log("加载叫分倍数"+ newpb.RoomInfo.Multiply);
                    //加载叫分预设
                    if (ddz.seatId == newpb.TurnSid)
                    {
                        if (newpb.RoomInfo.Multiply == 0)
                        {
                            CallScore = NGUITools.AddChild(Root, (GameObject)(Resources.Load(GameDDZPrafabPath.CallScore)));
                        }
                        else if (newpb.RoomInfo.Multiply == 1)
                        {
                            CallScore = NGUITools.AddChild(Root, (GameObject)(Resources.Load(GameDDZPrafabPath.CallScore2)));
                        }
                        else if (newpb.RoomInfo.Multiply == 2)
                        {
                            CallScore = NGUITools.AddChild(Root, (GameObject)(Resources.Load(GameDDZPrafabPath.CallScore3)));
                        }
                        
                    }
                    LoadTimeObj(newpb.TurnSid, false);
                    //加载底牌 三张牌
                    LastThreeCards = NGUITools.AddChild(Root, (GameObject)(Resources.Load(GameDDZPrafabPath.LastThreeCards)));
                }
                
            }

        }
        
       
        
    }
    #endregion 重连

    void LoadTimeObj(int seatid,bool destroy) {
        if (destroy) {
            Destroy(Time);
        }
        int tempIndex = ddz.returnOtherSeatIndex(seatid);
        Time = NGUITools.AddChild(gameObject, (GameObject)(Resources.Load(GameDDZPrafabPath.Time)));
        if (tempIndex == 0)
        {
            Time.transform.localPosition = new Vector3(38, -23, 0);
        }
        else if (tempIndex == 2)
        {
            Time.transform.localPosition = new Vector3(-316, 66, 0);
        }
        else if (tempIndex == 1)
        {
            Time.transform.localPosition = new Vector3(294, 66, 0);
        }
    }

    
}
